package com.scd.encrypt.utils;

import java.io.FileInputStream;
import java.io.InputStream;
import java.io.RandomAccessFile;

import sun.misc.BASE64Decoder;       
import sun.misc.BASE64Encoder; 

@SuppressWarnings("restriction")
public class Base64Util {
	 /**     
     * BASE64解密    
   * @param key           
     * @return           
     * @throws Exception           
     */                
    public static byte[] decryptBASE64(String key) throws Exception {
        return (new BASE64Decoder()).decodeBuffer(key);
    }                 
                    
    /**          
     * BASE64加密    
    * @param key           
     * @return           
     * @throws Exception           
     */                
    public static String encryptBASE64(byte[] key) throws Exception {
        return (new BASE64Encoder()).encodeBuffer(key);
    }
    
    /** 
     * 图片BASE64 编码 
     *  
     * @author zhujie 
     */  
    public static String getPicBASE64(String picPath) {  
        String content = null;  
        try {  
            InputStream inputStream = new FileInputStream(picPath);  
            byte[] bytes = new byte[inputStream.available()];  
            inputStream.read(bytes);  
            content = new sun.misc.BASE64Encoder().encode(bytes);
            inputStream.close();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return content;  
    }  
      
    /** 
     * 对图片BASE64 解码 
     *  
     * @author zhujie 
     */  
    public static void formatBASE64Img(String str, String picPath) {  
        try {
        	BASE64Decoder base64Decoder = new BASE64Decoder();
            byte[] result = base64Decoder.decodeBuffer(str.trim());
            // r,rw,rws,rwd
            RandomAccessFile inOut = new RandomAccessFile(picPath, "rw");
            inOut.write(result);
            inOut.close();
        } catch (Exception e) {
            e.printStackTrace();
        }  
    }  
    
    public static void main(String[] args) throws Exception {
    	String data = "sss成都";
    	String base64en = encryptBASE64(data.getBytes("utf8"));
    	System.out.println(base64en);
    	byte[] debyte = decryptBASE64(base64en);
    	System.out.println(new String(debyte, "utf8"));
    	String imgpath = "C:/Users/swx615626/Desktop/FILE/PIC/" + "timg.jpg";
    	String picBase64 = getPicBASE64(imgpath);
    	String outPath = "C:/Users/swx615626/Desktop/FILE/PIC/" + "timgtest.jpg";
    	formatBASE64Img(picBase64, outPath);
    }
}
